#include "debug.hpp"

#ifdef __linux__

#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>

/*
 * link using flag -rdynamic for gcc linker to show function names
 */
void debug_init(void)
{
	signal(SIGSEGV, debug_set_hook_on_crush);
}

void debug_set_hook_on_crush(int signal)
{

	void *buffer[1024] =
	{ 0 };

	int nptrs = backtrace(buffer, sizeof(buffer) / sizeof(buffer[0]));
	fprintf(stderr, "backtrace() returned %d addresses\n", nptrs);

	backtrace_symbols_fd(buffer, nptrs, STDERR_FILENO);
	exit(EXIT_FAILURE);
}

static char * str_replase_char(char * str, int ch)
{
	char * start = str;
	while ((start = strchr(start, (int) '\"')))
	{
		*start = '\'';
	}
	return str;
}

void debug_message_box(const char* title, const char* message)
{
	char * title_tmp = strdup(title);
	char * message_tmp = strdup(message);
	title_tmp = str_replase_char(title_tmp, (int) '\"');
	message_tmp = str_replase_char(message_tmp, (int) '\"');

	char str_buffer[4096] =
	{ 0 };
	snprintf(str_buffer, sizeof(str_buffer),
			"echo \"%s\" | xmessage -center -title \"%s\" -file -", message_tmp,
			title_tmp);

	free(title_tmp);
	free(message_tmp);

	if (0 != system(str_buffer))
	{
		fprintf(stderr, "%s %s",
				"Can't show message via xmessage command. Message: ", message);
	}
}

#else

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

void debug_init(void)
{}
void debug_set_hook_on_crush(int signal)
{}
void debug_message_box(const char* title, const char* message)
{
	MessageBoxA(0, message, title, MB_OK);
}

#endif
